package org.linlinjava.litemall.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linlinjava.litemall.db.dao.UserMapper;
import org.linlinjava.litemall.db.models.User;
import org.linlinjava.litemall.db.vo.UserVo;
import org.linlinjava.litemall.db.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Override
    public UserVo findUserVoById(Long userId) {
        User user = getById(userId);
        UserVo userVo = new UserVo();
        userVo.setNickname(user.getNickname());
        userVo.setAvatar(user.getAvatar());
        return userVo;
    }

    @Override
    public User queryByOid(String openId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getWeixinOpenid, openId));
    }

    @Override
    public IPage<User> querySelective(String username, String mobile, Integer pageNo, Integer pageSize) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.like(!StringUtils.isEmpty(username), "username", username);
        query.eq(!StringUtils.isEmpty(mobile), "mobile", mobile);
        Page<User> page = new Page<>(pageNo, pageSize);
        return baseMapper.selectPage(page, query);
    }

    @Override
    public int count() {
        return baseMapper.selectCount(new QueryWrapper<User>());
    }

    @Override
    public List<User> queryByUsername(String username) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", username);
        return baseMapper.selectList(query);
    }

    @Override
    public boolean checkByUsername(String username) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", username);
        return baseMapper.selectCount(query) > 0;
    }

    @Override
    public List<User> queryByMobile(String mobile) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("mobile", mobile);
        return baseMapper.selectList(query);
    }

    @Override
    public List<User> queryByOpenid(String openid) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("weixin_openid", openid);
        return baseMapper.selectList(query);
    }
}
